package com.qingcheng.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.Page;
import com.qingcheng.dao.*;
import com.qingcheng.domain.Goods;
import com.qingcheng.exception.YoException;
import com.qingcheng.pojo.goods.*;
import com.qingcheng.service.TbSpuService;
import com.qingcheng.util.CacheKey;
import com.qingcheng.util.IdWorker;
import com.qingcheng.util.PageUtil;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.*;


/**
*
* @author Simon
* @date 2020/07/27
*/
@Service
public class TbSpuServiceImpl implements TbSpuService {

    @Resource
    private TbSpuMapper tbSpuMapper;

    @Resource
    private SpuMapper spuMapper;

    @Resource
    private TbSkuMapper tbSkuMapper;

    @Resource
    private TbBrandMapper tbBrandMapper;

    @Autowired(required = false)
    private IdWorker idWorker;

    @Resource
    private TbCategoryMapper tbCategoryMapper;

    @Resource
    private TbCategoryBrandMapper tbCategoryBrandMapper;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Resource
    private RedisTemplate goodsRedisTemplate;


    @Override
    public boolean removeSpu(String id) {
        Example example = new Example(TbSku.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("spuId",id);
        int result = tbSkuMapper.deleteByExample(example);
        if ( result > 0 ) {
            result = tbSpuMapper.deleteByPrimaryKey(id);
            rabbitTemplate.convertAndSend("queue.standUD",id);
        }
        return result>0;
    }

    @Override
    public List<Long> counts() {
        ArrayList<Long> longs = new ArrayList<>();
        Long aLong = tbSpuMapper.marketableCount();
        Long aLong1 = tbSpuMapper.statusCount();
        longs.add(aLong);
        longs.add(aLong1);
        return longs;
    }

    @Override
    public PageUtil<TbSpu> CommodityRecyclingStation(Integer PageNum, Integer PageSize, TbSpu tbSpu) {
        Example example = new Example(TbSpu.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("isDelete","1");
        if(tbSpu != null){
            if(!StringUtils.isEmpty(tbSpu.getName())){
                criteria.andLike("name","%"+tbSpu.getName()+"%");
            }
            if(!StringUtils.isEmpty(tbSpu.getCategory3Id())){
                criteria.andEqualTo("category3Id",tbSpu.getCategory3Id());
            }
            if(!StringUtils.isEmpty(tbSpu.getBrandId())){
                criteria.andEqualTo("brandId",tbSpu.getBrandId());
            }
        }
        PageHelper.startPage(PageNum,PageSize);
        Page<TbSpu> pages = (Page<TbSpu>) tbSpuMapper.selectByExample(example);
        return new PageUtil<>(pages.getTotal(),pages.getResult());
    }

    /**
     * @param id 根据id修改状态
     * @return 逻辑删除和数据回复
     */
    @Override
    public boolean removeSpuIsDelete(String id) {
        TbSpu spu = tbSpuMapper.selectByPrimaryKey(id);
        // 这是还没有被删除的数据
        if("0".equals(spu.getIsDelete())){
            // 修改上架的状态，0为下架
            spu.setIsMarketable("0");
            spu.setIsDelete("1");
        }
        else{
            // 商品的恢复
            spu.setIsMarketable("1");
            spu.setIsDelete("0");
        }
        int result = tbSpuMapper.updateByPrimaryKeySelective(spu);
        // 逻辑删除之后的删除
        rabbitTemplate.convertAndSend("queue.standUD",spu.getId());
        return result>0;
    }

    @Override
    public int putMany(Long[] ids) {
        TbSpu tbSpu = new TbSpu();
        tbSpu.setIsMarketable("1"); // 上架
        // 批量修改
        Example example = new Example(TbSpu.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andIn("id", Arrays.asList(ids)); // ids
        criteria.andEqualTo("0"); // 下架的商品
        criteria.andEqualTo("status","1"); // 审核通过的
        criteria.andEqualTo("isDelete","0"); // 非删除的
        return tbSpuMapper.updateByExampleSelective(tbSpu, example);
    }

    /**
     * 上下架
     * @param id 根据id修改数据
     * @return
     */
    @Override
    public boolean put(String id) {
        TbSpu tbSpu = tbSpuMapper.selectByPrimaryKey(id);
        if("0".equals(tbSpu.getStatus()))
            throw new YoException("此商品未通过审核",567);
        tbSpu.setIsMarketable("1");
        int result = tbSpuMapper.updateByPrimaryKeySelective(tbSpu);
        // 上架
        rabbitTemplate.convertAndSend("queue.standUD",tbSpu.getId());
        return result>0;
    }

    @Override
    public boolean pull(String id) {
        TbSpu tbSpu = tbSpuMapper.selectByPrimaryKey(id);
        tbSpu.setIsMarketable("0");
        int result = tbSpuMapper.updateByPrimaryKeySelective(tbSpu);
        // 下架
        rabbitTemplate.convertAndSend("queue.standUD",tbSpu.getId());
        return result>0;
    }


    @Override
    @Transactional
    public boolean audit(TbSpu tbSpu) {
        if("1".equals(tbSpu.getStatus()))
            tbSpu.setIsMarketable("1"); // 自动上架
        tbSpuMapper.updateByPrimaryKeySelective(tbSpu);
        // 审核通过之后的同时也往es中插入数据
        rabbitTemplate.convertAndSend("queue.standUD",tbSpu.getId());
        //2.记录商品审核记录 学员实现
        //3.记录商品日志 学员实现
        return false;
    }

    /**
     * @param id 查询id
     * @return 数据回显
     */
    @Override
    public Goods findGoodsById(String id) {
        // 查询spu
        TbSpu tbSpu = tbSpuMapper.selectByPrimaryKey(id);
        // 查询sku列表
        Example exception = new Example(TbSku.class);
        Example.Criteria criteria = exception.createCriteria();
        criteria.andEqualTo("spuId",id);
        List<TbSku> tbSkus = tbSkuMapper.selectByExample(exception);
        // 封装返回
        Goods goods = new Goods();
        goods.setSpu(tbSpu);
        goods.setSkuList(tbSkus);
        return goods;
    }

    /**
     * SPU && SKU 数据的保存/修改
     * @param goods 商品组合实体类
     * @return 所有流程无误则返回true
     */
    @Override
    @Transactional
    public boolean saveGoods(Goods goods) {
        boolean result = false;
        String sn = idWorker.nextId()+"";
        // 保存spu
        TbSpu tbSpu = goods.getSpu();
        TbBrand tbBrand = tbBrandMapper.selectByPrimaryKey(tbSpu.getBrandId());
        if(StringUtils.isEmpty(tbSpu.getId())) {
            tbSpu.setId(idWorker.nextId() + "");
            // 默认添加不上架
            tbSpu.setIsMarketable("0");
            // 0表示未删除
            tbSpu.setIsDelete("0");
            // 0表示为展示到广告栏
            tbSpu.setAdStatus("0");
            if (StringUtils.isEmpty(tbSpu.getSn())) {
                // 商品的货号
                tbSpu.setSn(sn);
            }
            int insert = tbSpuMapper.insert(tbSpu);
            result = insert>0;
        }else {
            // 删除原来的sku列表
            Example example = new Example(TbSku.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("spuId",tbSpu.getId());
            tbSkuMapper.deleteByExample(example);
            // 执行spu的修改
            int update = tbSpuMapper.updateByPrimaryKeySelective(tbSpu);
            result = update>0;
        }
        Date date = new Date();
        // 分类对象，保存sku
        TbCategory tbCategory = tbCategoryMapper.selectByPrimaryKey(tbSpu.getCategory3Id());
        List<TbSku> skuList = goods.getSkuList();
        for (TbSku t :
                skuList) {
            // 列表数据不存在则添加id和创建时间
            if(t.getId() == null) {
                t.setId(idWorker.nextId() + "");
                t.setCreateTime(date);//创建日期
            }
            if (StringUtils.isEmpty(t.getSn())) {
                t.setSn(sn);
            }
            t.setSpuId(tbSpu.getId());
            // skuName = spuName + 规格值列表
            String name = tbSpu.getName();
            // 不启用规格的处理
            if(StringUtils.isEmpty(t.getSpec())){
                t.setSpec("{}");
            }
            //sku.getSpec() {"颜色":"红","机身内存":"64G"}
            Map<String, String> specMap = JSON.parseObject(t.getSpec(),
                    Map.class);
            for (String value : specMap.values()) {
                name += " " + value;
            }
            t.setName(name);//名称
            t.setUpdateTime(date);//修改日期
            t.setCategoryId(tbSpu.getCategory3Id());//分类id
            t.setCategoryName(tbCategory.getName());//分类名称
            t.setCommentNum(0);//评论数
            t.setSaleNum(0);//销售数量
            t.setStatus("1");// 商品状态 1-正常，2-下架，3-删除
            t.setBrandName(tbBrand.getName());
            tbSkuMapper.insert(t);
            // 建立分类与品牌的关联
            TbCategoryBrand tbCategoryBrand = new TbCategoryBrand();
            tbCategoryBrand.setBrandId(tbSpu.getBrandId());
            tbCategoryBrand.setCategoryId(tbSpu.getCategory3Id());
            int count = tbCategoryBrandMapper.selectCount(tbCategoryBrand);
            if (count == 0) {
                int insert = tbCategoryBrandMapper.insert(tbCategoryBrand);
                result = insert>0;
            }
        }
        return result;
    }

    @Override
    public List<TbSpu> queryAll() {
        List<TbSpu> tbSpu = tbSpuMapper.selectAll();
            return tbSpu;
    }

    @Override
    public PageUtil<TbSpu> queryAudit(Integer pageNum, Integer pageSize, TbSpu tbSpu) {
        Example example=new Example(TbSpu.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("status","0");
        if(tbSpu != null){
            if(!StringUtils.isEmpty(tbSpu.getName())){
                criteria.andLike("name","%"+tbSpu.getName()+"%");
            }
            if(!StringUtils.isEmpty(tbSpu.getCategory3Id())){
                criteria.andEqualTo("category3Id",tbSpu.getCategory3Id());
            }
            if(!StringUtils.isEmpty(tbSpu.getBrandId())){
                criteria.andEqualTo("brandId",tbSpu.getBrandId());
            }
        }
        PageHelper.startPage(pageNum,pageSize);
        Page<TbSpu> pages = (Page<TbSpu>) tbSpuMapper.selectByExample(example);
        return new PageUtil<>(pages.getTotal(),pages.getResult());
    }

    @Override
    public PageUtil<TbSpu> findListAll(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        Page<TbSpu> pages = (Page<TbSpu>) tbSpuMapper.selectAll();
        PageUtil<TbSpu> pageUtil=new PageUtil<>();
        pageUtil.setRows(pages.getResult());
        pageUtil.setTotal(pages.getTotal());
        return pageUtil;
    }


    @Override
    public PageUtil<TbSpu> pageQueryByAll(Integer pageNum, Integer pageSize, TbSpu tbSpu) {

        Example example=new Example(TbSpu.class);
        Example.Criteria criteria = example.createCriteria();
        if(tbSpu != null){
            if(!StringUtils.isEmpty(tbSpu.getName())){
                criteria.andLike("name","%"+tbSpu.getName()+"%");
            }
            if(!StringUtils.isEmpty(tbSpu.getCategory3Id())){
               criteria.andEqualTo("category3Id",tbSpu.getCategory3Id());
            }
            if(!StringUtils.isEmpty(tbSpu.getBrandId())){
                criteria.andEqualTo("brandId",tbSpu.getBrandId());
            }
        }
        // 没有经过逻辑删除的数据
        criteria.andEqualTo("isDelete","0");
        PageHelper.startPage(pageNum,pageSize);
        Page<TbSpu> pages = (Page<TbSpu>) tbSpuMapper.selectByExample(example);
        PageUtil<TbSpu> pageUtil=new PageUtil<>();
        pageUtil.setRows(pages.getResult());
        pageUtil.setTotal(pages.getTotal());
        return pageUtil;
     }


    @Override
    public boolean saveTbSpu(TbSpu tbSpu) {
        int insert = tbSpuMapper.insert(tbSpu);
        if(insert>0){
            return true;
        }
        return false;
    }

    @Override
    public boolean updateTbSpu(TbSpu tbSpu) {
        int i = tbSpuMapper.updateByPrimaryKeySelective(tbSpu);
        if(i>0){
            return true;
        }
        return false;
    }


    @Override
    public boolean deleteById(Integer id) {
        int i = tbSpuMapper.deleteByPrimaryKey(id);
        if(i>0){
            return true;
        }
        return false;
    }

    @Override
    public TbSpu findById(String id) {
        TbSpu tbSpu = tbSpuMapper.selectByPrimaryKey(id);
        return tbSpu;
    }

    /**
     * 商品热卖显示
     * */
    @Override
    public List<Map> bestgoods() {
        List<Map> map = (List<Map>) goodsRedisTemplate.boundValueOps(CacheKey.BEST).get();
        if(map==null){
            bestcache();
            return (List<Map>) goodsRedisTemplate.boundValueOps(CacheKey.BEST).get();
        }
        return map;
    }

    /*
     * 热卖缓存
     * */
    @Override
    public void bestcache() {
        // 热卖商品的时间多少天内销量最多算热卖
        LocalDate date1=LocalDate.now().minusDays(7);
        LocalDate date2=LocalDate.now();

        // 查询出热卖商品
        List<Map> best=spuMapper.bestgoods(date1,date2);
        if(best.size()<4){
            best=spuMapper.nullbestgoods();
        }
         goodsRedisTemplate.boundValueOps(CacheKey.BEST).set(best);
    }

    /**
     * 最新商品显示
     * */
    @Override
    public List<Map> newproduct() {
        return spuMapper.newproduct();
    }

    /**
     * 首页商品推荐
     * 根据你已经购买的商品查询
     * 没有则随机
     * */
    @Override
    public List<Map> like() {

        List<String> item=spuMapper.likeid();
        List<Map> like;
        List<Map> list=new LinkedList<>();
        if(item.size()<2){
            list = spuMapper.nullLike();
        }else {
            for(String id:item){
                like = spuMapper.like(id);
                list.addAll(like);
            }
            if(list.size()<6){
                list = spuMapper.nullLike();
            }
        }

        return list;
    }

    @Override
    public PageUtil<TbSpu> adQueryAll(Integer pageNum, Integer pageSize, TbSpu tbSpu) {
        Example example=new Example(TbSpu.class);
        Example.Criteria criteria = example.createCriteria();
        if(tbSpu != null){
            if(!StringUtils.isEmpty(tbSpu.getName())){
                criteria.andLike("name","%"+tbSpu.getName()+"%");
            }
            if(!StringUtils.isEmpty(tbSpu.getCategory3Id())){
                criteria.andEqualTo("category3Id",tbSpu.getCategory3Id());
            }
            if(!StringUtils.isEmpty(tbSpu.getBrandId())){
                criteria.andEqualTo("brandId",tbSpu.getBrandId());
            }
        }
        // 没有经过逻辑删除的数据
        criteria.andEqualTo("isDelete","0");
        criteria.andEqualTo("adStatus","0");
        PageHelper.startPage(pageNum,pageSize);
        Page<TbSpu> pages = (Page<TbSpu>) tbSpuMapper.selectByExample(example);
        PageUtil<TbSpu> pageUtil=new PageUtil<>();
        pageUtil.setRows(pages.getResult());
        pageUtil.setTotal(pages.getTotal());
        return pageUtil;
    }

    @Override
    public int updateAdStatus(String spuId) {
        TbSpu tbSpu = tbSpuMapper.selectByPrimaryKey(spuId);
        tbSpu.setAdStatus("1");
        int result = tbSpuMapper.updateByPrimaryKey(tbSpu);
        return result;
    }
}
